package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"shopps/models"
)

type ShopController struct {
	beego.Controller
}

type Json struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	typed := c.GetString("typed")
	img := c.GetString("img")
	status := c.GetString("status")

	shop := models.Shop{
		Name:   name,
		Price:  price,
		Typed:  typed,
		Img:    img,
		Status: status,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		res := Json{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Json{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		res := Json{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Json{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

type JsonR struct {
	Code    int
	Msg     string
	Data    interface{}
	Page    int
	Sumpage int
	Count   int64
	Size    int
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size := 5
	var count int64
	models.DB.Model(models.Shop{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	var allstu []models.Shop
	err := models.DB.Offset(offset).Limit(size).Find(&allstu).Error
	if err != nil {
		res := Json{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code:    200,
			Msg:     "添加成功",
			Data:    allstu,
			Page:    page,
			Sumpage: sumpage,
			Count:   count,
			Size:    size,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
